<template>
    <MenuPage
        :data="resData.list"
        :columns="columns"
        :title="' '"
        :page.sync="queryParams.pageIndex"
        :size.sync="queryParams.pageSize"
        :total="resData.total"
        :loading="resData.loading"
        class="my-menu-page"
        @queryFun="getTableList">
        <template slot="search">
            <Button
                type="primary"
                ghost
                icon="ios-add"
                style="height: 32px;margin-left: 9px;"
                @click="showModal()">创建POC
            </Button>
            <Select filterable transfer 
                v-model="queryParams.languageType" 
                placeholder="语言类型"
                clearable
                filterable
                style="width:150px;text-align: left;margin-left: 15px;" 
                @on-change="changePageNow(1)">
                <Option v-for="(item, index) in languageOptions" :value="index" :key="index">{{ item }}</Option>
            </Select>
            <Select filterable transfer 
                v-model="queryParams.verify" 
                placeholder="是否验证"
                clearable
                filterable
                style="width:150px;text-align: left;margin-left: 15px;" 
                @on-change="changePageNow(1)">
                <Option :value="0">未验证</Option>
                <Option :value="1">已验证</Option>
            </Select>
            <Button
                type="primary"
                ghost
                style="height: 32px;margin-left: 9px;"
                @click="refreshQueryParams()">
                <i class="el-icon-refresh-right" />
            </Button>
        </template>
        <Modal
            v-model="modalData.show"
            :title="`${isAdd ? '创建' : '修改'}POC`"
            @on-visible-change="changeVisible"
            class="my-modal">
            <Form 
                ref="formInline"
                :label-width="130"
                :model="formInline" 
                :rules="ruleInline">
                <FormItem prop="name" label="公用漏洞名称">
                    <Input clearable v-model="formInline.name" disabled></Input>
                </FormItem>
                <FormItem prop="poc"  label="POC">
                    <Input clearable v-model="formInline.poc" type="textarea" :rows="3"></Input>
                </FormItem>
                <FormItem prop="languageType" label="语言类型">
                    <Select filterable transfer filterable clearable v-model="formInline.languageType" placeholder="">
                        <Option v-for="(item, index) in languageOptions" :value="index" :key="index">{{ item }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="verify"  label="是否验证">
                    <RadioGroup v-model="formInline.verify">
                        <Radio :label="1">
                            <span>已验证</span>
                        </Radio>
                        <Radio :label="0">
                            <span>未验证</span>
                        </Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem prop="verifyTime" label="验证时间" v-if="formInline.verify === 1">
                    <DatePicker 
                        type="datetime" 
                        format="yyyy-MM-dd HH:mm:ss" 
                        placeholder="" 
                        v-model="formInline.verifyTime" 
                        :editable="false"
                        class="my-date-picker"></DatePicker>
                </FormItem>
            </Form>
            <div slot="footer" class="footer">
                <Button @click="modalData.show = false">取消</Button>
                <Button @click="saveVulnerabilityPoc" :loading="modalData.loading" type="primary">确定</Button>
            </div>
        </Modal>
    </MenuPage>
</template>

<script>
import { queryVulnerabilityPocList, addVulnerabilityPoc, updateVulnerabilityPoc, deleteVulnerabilityPoc } from '@/view/testPlatform/vulnerability/api/vulnerabilityPoc'
import { debounce } from '@/libs/utils'
import moment from 'moment'

export default {
    name: 'PocManage',
    components: { 
    },
    props: {
        vulnerabilityId: {
            type: String,
            default: ''
        },
        vulnerabilityName: {
            type: String,
            default: ''
        },
        isPublic: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            languageOptions: ['C/C++', 'java', 'php', 'python', 'go'],
            drawerData: {
                show: false
            },
            resData: {
                total: 0,
                list: [],
                loading: true
            },
            queryParams: {
                publicVulnerabilityId: this.vulnerabilityId,
                pageIndex: 1,
                pageSize: 10,
                languageType: '',
                verify: ''
            },
            columns: [
                {
                    title: '语言类型',
                    key: 'languageType',
                    render: (h, params) => {
                        return h('span', this.languageOptions[params.row.languageType])
                    }
                },
                {
                    title: 'POC',
                    key: 'poc',
                    tooltip: true
                },
                {
                    title: '创建者',
                    key: 'creatorName',
                    tooltip: true
                },
                {
                    title: '创建时间',
                    key: 'created',
                    tooltip: true
                },
                {
                    title: '是否验证',
                    placement: 'top-right',
                    key: 'type',
                    render: (h, params) => {
                        return h('Tag', {
                            props: {
                                color: params.row.verify ? '#19be6b' : '#ff9900'
                            },
                            style: {
                                width: '60px',
                                'text-align': 'center'
                            }
                        }, params.row.verify ? '已验证' : '未验证')
                    }
                },
                {
                    title: '操作',
                    width: 100,
                    slot: 'action',
                    opList: [
                        {
                            txt: '修改',
                            on:{
                                click:(data) => {
                                    this.showModal(data)
                                }
                            },
                        },
                        {
                            txt: '删除',
                            tooltip: true,
                            type: 'delete',
                            title: '确定要删除吗？',
                            on:{
                                click:(data,e) => {
                                    this.deleteItem([data.id], data.projectId)
                                }
                            },
                        }
                    ]
                }
            ],
            modalData: {
                show: false,
                loading: false
            },
            formInline: {
                name: '',
                publicVulnerabilityId: '',
                languageType: '',
                poc: '',
                verify: 1,
                verifyTime: '',
                bindType: this.isPublic ? 0 : 1
            },
            ruleInline: {
                name: [
                    { required: true, message: '漏洞名称不能为空', trigger: 'blur,change' },
                    { type:'string',max: 2000,trigger:'blur,change',message:'最多输入2000个字符' },
                    // { validator:validateName, trigger: 'blur,change' }
                ],
                poc: [
                    { required: true, message: 'POC类型不能为空', trigger: 'blur,change' }
                ],
                languageType: [
                    { required: true, type:'number', message: '语言类型不能为空', trigger: 'blur,change' }
                ],
                verify: [
                    { required: true, type:'number', message: '是否验证不能为空', trigger: 'blur,change' }
                ],
                verifyTime: [
                    { required: true, type: 'object', message: '验证时间不能为空', trigger: 'blur,change' }
                ]
            },
            isAdd: false
        }
    },
    mounted(){
    },
    methods: {
        // 隐藏模态框时，重置表单数据
        changeVisible(type) {
            this.$nextTick(() => {
                if (!type) {
                    this.$refs.formInline.resetFields()
                    this.modalData.loading = false
                }
            })
        },
        // 防抖方法，用于输入型查询
        debounceFn: debounce(function() {
            this.changePageNow(1);
        }),
        // 重置搜索条件并查询数据
        refreshQueryParams() {
            this.queryParams =  {
                publicVulnerabilityId: this.vulnerabilityId,
                pageIndex: 1,
                pageSize: 10,
                languageType: '',
                verify: ''
            },
            this.getTableList()
        },
        // 查询指定页数据
        changePageNow(val) {
            this.queryParams.pageIndex = val;
            this.getTableList();
        },
        // 获取POC列表
        getTableList(isRefresh) {
            if (!isRefresh) { // 非定时器触发的刷新列表的操作，需要设置loading状态
                this.resData.loading = true
            }
            queryVulnerabilityPocList(this.queryParams).then(({ code, message, data = {} }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.resData = {
                    total: data.total || 0,
                    list: data.items || []
                }
            }).catch(() => {
                this.$Message.error('获取POC列表异常')
            })
        },
        // 打开模态框
        showModal(data) {
            this.isAdd = !data
            this.modalData.show = true
            let obj = data || { 
                name: '',
                publicVulnerabilityId: this.vulnerabilityId,
                languageType: '',
                poc: '',
                verify: 1,
                verifyTime: '',
                bindType: this.isPublic ? 0 : 1
            }
            this.formInline = Object.assign({}, obj, {
                name: this.vulnerabilityName
            })
            this.$set(this.formInline, 'verify', this.formInline.verify ? 1 : 0)
        },
        // 保存数据
        saveVulnerabilityPoc() {
            this.$refs.formInline.validate(valid => {
                if (valid) {
                    this.modalData.loading = true
                    let apiName = this.isAdd ? addVulnerabilityPoc : updateVulnerabilityPoc
                    let data = Object.assign({}, this.formInline)
                    data.verify = data.verify === 1
                    if (typeof data.verifyTime !== 'string') {
                        data.verifyTime = moment(data.verifyTime).format('YYYY-MM-DD HH:mm:ss')
                    }
                    if (!data.verify) {
                        data.verifyTime = ''
                    }
                    if (this.isAdd) { // 创建操作确认把id删掉，避免造成错误
                        delete data.id
                    }
                    apiName(data).then(({ code, message, data = {} }) => {
                        if (code !== 1) {
                            this.$Message.warning(message)
                            return
                        }
                        // 创建成功
                        this.$Message.success(`${this.isAdd ? '创建' : '修改'}POC成功`)
                        this.modalData.show = false
                        this.refreshQueryParams()
                        this.$emit(this.isAdd ? 'add-success' : 'update-success', data)
                    }).catch(() => {
                        this.$Message.error(`${this.isAdd ? '创建' : '修改'}POC异常`)
                    }).finally(() => {
                        this.modalData.loading = false
                    })
                }
            })
        },
        // 删除日志
        deleteItem(ids) {
            deleteVulnerabilityPoc(ids).then(({ code, message }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.$Message.success(`删除POC成功`)
                // 删除后展示当前页，当前页没有数据展示前一页
                this.queryParams.pageIndex = (this.resData.list.length == ids.length && this.queryParams.pageIndex > 1) ?
                                this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
                this.getTableList()
                this.$emit('delete-success', ids[0])
            }).catch(() => {
                this.$Message.error(`删除POC异常`)
            })
        },
    },
}
</script>

<style scoped>
.my-modal .flex {
    display: flex;
    line-height: 2;
    align-items: baseline;
}
.flex.column {
    flex-direction: column;
}
.my-modal .flex .row-label {
    margin-right: 6px;
    width: 90px;
    text-align: right;
    font-size: 14px;
    color: #515a6e;
}
.flex.column .row-label {
    margin-right: 0;
    width: 100%;
    text-align: left;
}
.row-text {
    flex: 1;
    word-break: break-word;
}
.item-table {
    display: table;
    width: 100%;
    border: 1px solid #eee;
    table-layout: fixed;
    word-break: break-all;
}

.item-table p {
    display: table-row;
    line-height: 36px;
    text-align: center;
}

.item-table p span {
    display: table-cell;
    border-bottom: 1px solid #eee;
}

.bespread {
    width: 100%;
}

.my-drawer /deep/ .ivu-drawer-body {
    background-color: #f0f2f5;
}

.num-group {
    display: flex;
    justify-content: space-around;
    width: 100%;
}
.item-table {
    display: table;
    width: 100%;
    border: 1px solid #eee;
    table-layout: fixed;
    word-break: break-all;
}

.item-table p {
    display: table-row;
    line-height: 36px;
    text-align: center;
}

.item-table p span {
    display: table-cell;
    border-bottom: 1px solid #eee;
}
</style>